import 'package:flutter/material.dart';
import 'package:pcms/config/air_conditioner_config.dart';
import 'package:pcms/models/air_conditioner_status.dart';

class AirConditionerStatusWidget extends StatefulWidget {
  final String title;
  const AirConditionerStatusWidget({super.key, required this.title});

  @override
  State<AirConditionerStatusWidget> createState() => _AirConditionerStatusWidgetState();
}

class _AirConditionerStatusWidgetState extends State<AirConditionerStatusWidget> {
  List<AirConditionerStatus> units = [];
  bool isLoading = true;
  String? errorMessage;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      setState(() {
        isLoading = true;
        errorMessage = null;
      });
      
      final data = widget.title == 'XF-01空调机组信息'
          ? await getXf01Data()
          : await getXf02Data();
      
      setState(() {
        units = data;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        errorMessage = '加载空调机组数据失败: $e';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitle(),
          const Center(
            child: Padding(
              padding: EdgeInsets.all(16.0),
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
          ),
        ],
      );
    }
    
    if (errorMessage != null) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitle(),
          Center(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Text(
                    errorMessage!,
                    style: const TextStyle(color: Colors.red, fontSize: 12),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 8),
                  ElevatedButton(
                    onPressed: _loadData,
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          ),
        ],
      );
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitle(),
          _buildUnitsGrid(),
        ],
      ),
    );
  }

  Widget _buildTitle() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(2.0, 4.0, 16.0, 8.0),
      child: Row(
        children: [
          Icon(
            Icons.ac_unit,
            color: const Color(0xFF0A79DF),
            size: 14,
          ),
          const SizedBox(width: 6),
          Container(
            width: 2,
            height: 12,
            decoration: BoxDecoration(
              color: const Color(0xFF0A79DF),
              borderRadius: BorderRadius.circular(1),
            ),
            margin: const EdgeInsets.only(right: 6),
          ),
          Text(
            widget.title,
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: Colors.white,
              letterSpacing: 0.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUnitsGrid() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final itemWidth = (constraints.maxWidth - 16) / 3; // 3 items per row
        return Wrap(
          spacing: 4.0,
          runSpacing: 4.0,
          children: units.map((unit) {
            return SizedBox(
              width: itemWidth,
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 2),
                child: Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFF0B1A3E),
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(
                      color: unit.status ? const Color(0xFF0A79DF).withOpacity(0.3) : Colors.red.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 8,
                          height: 8,
                          decoration: BoxDecoration(
                            color: unit.status ? const Color(0xFF0A79DF) : Colors.red,
                            borderRadius: BorderRadius.circular(4),
                            boxShadow: [
                              BoxShadow(
                                color: (unit.status ? const Color(0xFF0A79DF) : Colors.red).withOpacity(0.3),
                                blurRadius: 6,
                                spreadRadius: 2,
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 8),
                        Flexible(
                          child: Text(
                            '${unit.label}(${unit.shortAddress})',
                            style: TextStyle(
                              color: unit.status ? Colors.white : Colors.white70,
                              fontSize: 12,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          }).toList(),
        );
      },
    );
  }
}